'use client';

import React, { useState, useEffect, useMemo } from 'react';
import { useParams } from 'next/navigation';
import Navbar from '@/components/ui/navbar';
import AppHeader from '@/components/ui/app-header';
import { useSession } from 'next-auth/react';
import { ProjectStats, StatsFilter, ExportFormat } from '@/types/stats';
import { 
  CalendarDaysIcon, 
  DocumentArrowDownIcon,
  FunnelIcon,
  ChartBarIcon,
  UserGroupIcon,
  ClockIcon,
  ArrowPathIcon
} from '@heroicons/react/24/outline';
import { projectApi } from '@/lib/api';
import { toast } from '@/components/ui/use-toast';
import jsPDF from 'jspdf';
import { saveAs } from 'file-saver';

const exportData = async (projectId: string, format: ExportFormat, stats: ProjectStats | null, projectName: string = '项目') => {
  if (!stats) {
    toast({
      title: '导出失败',
      description: '没有可导出的统计数据',
      variant: 'destructive'
    });
    return;
  }
  
  const now = new Date();
  const dateStr = now.toISOString().split('T')[0];
  const filename = `${projectName}-统计数据-${dateStr}`;
  
  try {
    if (format === 'pdf') {
      // PDF导出 - 使用支持中文的配置
      const pdf = new jsPDF({
        orientation: 'portrait',
        unit: 'mm',
        format: 'a4',
      });
      
      // 添加中文支持 - 使用Base64编码的方式添加中文支持
      // 注：此方法适用于简单的中文显示，更复杂的场景可能需要引入完整的字体文件
      
             // 创建自定义渲染函数处理中文
      const renderText = (text: string, x: number, y: number, options: { fontSize?: number; fontFamily?: string } = {}) => {
        // 将中文文本转为图片方式渲染
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        if (!ctx) return;
        
        // 设置字体大小和样式
        const fontSize = options.fontSize || 12;
        const fontFamily = options.fontFamily || 'Arial, "Microsoft YaHei", "微软雅黑", STXihei, "华文细黑", sans-serif';
        
        ctx.font = `${fontSize}px ${fontFamily}`;
        const textWidth = ctx.measureText(text).width;
        
        // 创建适当大小的画布
        canvas.width = textWidth + 4; // 添加一些边距
        canvas.height = fontSize * 1.5;
        
        // 重新设置字体，因为调整canvas大小后会重置
        ctx.font = `${fontSize}px ${fontFamily}`;
        ctx.fillStyle = '#000';
        ctx.textBaseline = 'top';
        
        // 渲染文本到画布
        ctx.fillText(text, 2, 2);
        
        // 转换为图片并添加到PDF
        try {
          const imgData = canvas.toDataURL('image/png');
          pdf.addImage(imgData, 'PNG', x, y - fontSize * 0.9, canvas.width * 0.26, canvas.height * 0.26);
        } catch (e) {
          console.error('文本渲染失败:', text, e);
        }
      };
      
      // 添加标题
      renderText(`${projectName} - 项目统计报告`, 20, 20, { fontSize: 18 });
      renderText(`生成日期: ${now.toLocaleString('zh-CN')}`, 20, 30, { fontSize: 12 });
      
      // 添加任务统计
      renderText('任务完成情况', 20, 45, { fontSize: 14 });
      renderText(`总任务数: ${stats.taskCompletion.total}`, 30, 55, { fontSize: 10 });
      renderText(`已完成任务: ${stats.taskCompletion.completed}`, 30, 60, { fontSize: 10 });
      renderText(`完成率: ${(stats.taskCompletion.completed / stats.taskCompletion.total * 100).toFixed(1)}%`, 30, 65, { fontSize: 10 });
      
      // 添加任务状态分布
      renderText('任务状态分布', 20, 80, { fontSize: 14 });
      renderText(`待处理: ${stats.taskCompletion.byStatus.todo}`, 30, 90, { fontSize: 10 });
      renderText(`进行中: ${stats.taskCompletion.byStatus.inProgress}`, 30, 95, { fontSize: 10 });
      renderText(`审核中: ${stats.taskCompletion.byStatus.review}`, 30, 100, { fontSize: 10 });
      renderText(`已完成: ${stats.taskCompletion.byStatus.done}`, 30, 105, { fontSize: 10 });
      
      // 添加时间跟踪
      renderText('时间跟踪', 20, 120, { fontSize: 14 });
      renderText(`预计工时: ${stats.timeTracking.estimatedHours} 小时`, 30, 130, { fontSize: 10 });
      renderText(`实际工时: ${stats.timeTracking.actualHours} 小时`, 30, 135, { fontSize: 10 });
      renderText(`剩余工时: ${stats.timeTracking.remainingHours} 小时`, 30, 140, { fontSize: 10 });
      
      // 添加团队成员活动
      renderText('团队成员活动', 20, 155, { fontSize: 14 });
      
      // 表头
      renderText('成员名称', 30, 165, { fontSize: 10 });
      renderText('已完成任务', 80, 165, { fontSize: 10 });
      renderText('评论数', 120, 165, { fontSize: 10 });
      renderText('最后活动', 160, 165, { fontSize: 10 });
      
      // 表格内容
      let yPos = 170;
      stats.memberActivity.forEach((member, index) => {
        if (yPos > 270) {
          // 添加新页
          pdf.addPage();
          yPos = 20;
          // 添加表头
          renderText('成员名称', 30, yPos, { fontSize: 10 });
          renderText('已完成任务', 80, yPos, { fontSize: 10 });
          renderText('评论数', 120, yPos, { fontSize: 10 });
          renderText('最后活动', 160, yPos, { fontSize: 10 });
          yPos += 10;
        }
        
        const lastActive = member.lastActive instanceof Date 
          ? member.lastActive.toLocaleDateString('zh-CN') 
          : new Date(member.lastActive).toLocaleDateString('zh-CN');
          
        renderText(member.name || '未知用户', 30, yPos, { fontSize: 10 });
        renderText(member.tasksCompleted.toString(), 80, yPos, { fontSize: 10 });
        renderText(member.commentsAdded.toString(), 120, yPos, { fontSize: 10 });
        renderText(lastActive, 160, yPos, { fontSize: 10 });
        
        yPos += 10;
      });
      
      pdf.save(`${filename}.pdf`);
      
      toast({
        title: '导出成功',
        description: `已导出为PDF文件: ${filename}.pdf`
      });
    } else if (format === 'excel') {
      // 生成CSV内容 - 添加UTF-8 BOM头确保Excel正确识别中文
      // BOM头是UTF-8编码的标识，可以让Excel正确打开中文CSV
      let csvContent = '\ufeff'; // UTF-8 BOM
      
      csvContent += '项目名称,' + projectName + '\n';
      csvContent += '导出日期,' + now.toLocaleString('zh-CN') + '\n\n';
      
      // 任务信息
      csvContent += '数据项,值\n';
      csvContent += '总任务数,' + stats.taskCompletion.total + '\n';
      csvContent += '已完成任务,' + stats.taskCompletion.completed + '\n';
      csvContent += '完成率,' + (stats.taskCompletion.completed / stats.taskCompletion.total * 100).toFixed(1) + '%\n\n';
      
      // 任务状态
      csvContent += '任务状态,数量\n';
      csvContent += '待处理,' + stats.taskCompletion.byStatus.todo + '\n';
      csvContent += '进行中,' + stats.taskCompletion.byStatus.inProgress + '\n';
      csvContent += '审核中,' + stats.taskCompletion.byStatus.review + '\n';
      csvContent += '已完成,' + stats.taskCompletion.byStatus.done + '\n\n';
      
      // 时间跟踪
      csvContent += '时间跟踪,小时\n';
      csvContent += '预计工时,' + stats.timeTracking.estimatedHours + '\n';
      csvContent += '实际工时,' + stats.timeTracking.actualHours + '\n';
      csvContent += '剩余工时,' + stats.timeTracking.remainingHours + '\n\n';
      
      // 团队成员
      csvContent += '成员名称,已完成任务,评论数,最后活动\n';
      stats.memberActivity.forEach(member => {
        // 处理CSV中可能出现的特殊字符，如逗号、引号等
        const name = (member.name || '未知用户').replace(/"/g, '""');
        const lastActive = member.lastActive instanceof Date 
          ? member.lastActive.toLocaleDateString('zh-CN') 
          : new Date(member.lastActive).toLocaleDateString('zh-CN');
          
        // 用双引号包围字段，避免逗号等特殊字符导致格式错误
        csvContent += `"${name}",${member.tasksCompleted},${member.commentsAdded},"${lastActive}"\n`;
      });
      
      // 创建Blob对象，明确指定UTF-8编码
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8' });
      
      // 下载文件
      saveAs(blob, `${filename}.csv`);
      
      toast({
        title: '导出成功',
        description: `已导出为CSV文件: ${filename}.csv`
      });
    } else {
      toast({
        title: '导出失败',
        description: `不支持的导出格式: ${format}`,
        variant: 'destructive'
      });
    }
  } catch (error) {
    console.error('导出统计数据失败:', error);
    toast({
      title: '导出失败',
      description: error instanceof Error ? error.message : '导出过程中出错',
      variant: 'destructive'
    });
  }
};

export default function ProjectStatsPage() {
  const params = useParams();
  const id = params?.id as string;
  const { status } = useSession();
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState<ProjectStats | null>(null);
  const [filter, setFilter] = useState<StatsFilter>({
    dateRange: 'month'
  });
  const [showFilters, setShowFilters] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [projectName, setProjectName] = useState<string>('项目');
  
  // 加载项目统计数据
  const loadStats = async () => {
    setLoading(true);
    
    // 显示加载通知
    toast({
      title: '正在加载统计数据',
      description: '请稍候...'
    });
    
    try {
      // 调用API获取项目统计数据
      // 注意：API当前不支持参数，所以暂时不传递
      const data = await projectApi.getProjectStats(id);
      console.log('获取到的统计数据:', data);
      
      // 适配API返回的数据结构为前端期望的ProjectStats类型
      if (data) {
        // 处理可能的API错误
        if (data.error) {
          throw new Error(data.error);
        }
        
        // 获取项目名称
        if (data.projectName) {
          setProjectName(data.projectName);
        }
        
        // 准备任务状态数据，确保所有必要的字段都有默认值
        const tasksByStatus = {
          todo: 0,
          inProgress: 0,
          review: 0,
          done: 0,
          ...(data.tasksByStatus || {})  // 合并API返回的数据
        };
        
        // 计算总任务数
        const totalTasks = data.overview?.totalTasks || 
                          (Object.values(tasksByStatus) as number[]).reduce((sum, count) => sum + count, 0) || 0;
        
        // 计算已完成任务数
        const completedTasks = data.overview?.completedTasks || 
                              tasksByStatus.done || 0;
        
        // 创建标准化的ProjectStats对象
        const adaptedStats: ProjectStats = {
          taskCompletion: {
            completed: completedTasks,
            total: totalTasks,
            byStatus: {
              todo: tasksByStatus.todo || 0,
              inProgress: tasksByStatus.inProgress || 0,
              review: tasksByStatus.review || 0,
              done: tasksByStatus.done || 0
            }
          },
          memberActivity: (data.memberStats || []).map((member: any) => ({
            userId: member.member?.id || '',
            name: member.member?.name || '未知用户',
            tasksCompleted: member.completedTasks || 0,
            commentsAdded: member.activity || 0,
            lastActive: new Date(member.lastActive || Date.now())
          })),
          timeTracking: {
            estimatedHours: data.overview?.estimatedHours || totalTasks * 2 || 0, // 假设每个任务2小时
            actualHours: data.overview?.actualHours || completedTasks * 2 || 0,     // 已完成任务 * 2小时
            remainingHours: data.overview?.remainingHours || (totalTasks - completedTasks) * 2 || 0
          },
          timeline: (data.trends?.taskCompletion || []).map((item: any) => ({
            date: item.date,
            completedTasks: item.count || 0,
            createdTasks: 0
          }))
        };
        
        setStats(adaptedStats);
        console.log('适配后的统计数据:', adaptedStats);
        
        // 清除任何之前的错误
        setError(null);
      } else {
        console.error('API返回的数据为空');
        throw new Error('获取统计数据失败：返回数据为空');
      }
    } catch (error) {
      console.error('获取项目统计数据失败:', error);
      setError(error instanceof Error ? error.message : '获取统计数据失败');
      
      // 显示错误通知
      toast({
        title: '统计数据加载失败',
        description: error instanceof Error ? error.message : '请稍后重试',
        variant: 'destructive'
      });
    } finally {
      setLoading(false);
    }
  };
  
  // 初始加载数据和筛选条件更改时重新加载
  useEffect(() => {
    if (id) {
      loadStats();
    }
  }, [id, filter.dateRange]);
  
  // 添加额外的安全检查
  const completionPercentage = stats && stats.taskCompletion && stats.taskCompletion.total > 0 ? 
    Math.round(((stats.taskCompletion.completed || 0) / stats.taskCompletion.total) * 100) : 0;
  
  const timeProgress = stats && stats.timeTracking && stats.timeTracking.estimatedHours > 0 ? 
    Math.round(((stats.timeTracking.actualHours || 0) / stats.timeTracking.estimatedHours) * 100) : 0;
  
  // 无数据时显示的信息
  const renderNoData = () => (
    <div className="mt-8 text-center py-12 px-4">
      <div className="text-gray-400 text-lg mb-4">无法加载项目统计数据</div>
      <button
        onClick={loadStats}
        className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none"
      >
        重试
      </button>
    </div>
  );
  
  return (
    <div className="min-h-screen bg-gray-50">
     
      <main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
        <div className="px-4 sm:px-0">
          <AppHeader
            title="项目统计"
            subtitle="查看项目进度和团队绩效数据"
            actions={
              <div className="flex space-x-2">
                <button
                  type="button"
                  onClick={loadStats}
                  className="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none"
                >
                  <ArrowPathIcon className={`h-4 w-4 mr-1 ${loading ? 'animate-spin' : ''}`} />
                  刷新
                </button>
                <button
                  type="button"
                  onClick={() => setShowFilters(!showFilters)}
                  className="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none"
                >
                  <FunnelIcon className="h-4 w-4 mr-1" />
                  筛选
                </button>
                <div className="relative inline-block text-left">
                  <div>
                    <button
                      type="button"
                      onClick={() => document.getElementById('export-menu')?.classList.toggle('hidden')}
                      className="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none"
                    >
                      <DocumentArrowDownIcon className="h-4 w-4 mr-1" />
                      导出
                    </button>
                  </div>
                  <div 
                    id="export-menu" 
                    className="hidden absolute right-0 mt-2 w-36 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 z-50"
                    onMouseLeave={() => document.getElementById('export-menu')?.classList.add('hidden')}
                  >
                    <div className="py-1" role="menu" aria-orientation="vertical">
                      <button
                        onClick={() => {
                          exportData(id as string, 'pdf', stats, projectName);
                          document.getElementById('export-menu')?.classList.add('hidden');
                        }}
                        className="text-gray-700 block w-full text-left px-4 py-2 text-sm hover:bg-gray-100"
                        role="menuitem"
                      >
                        PDF格式
                      </button>
                      <button
                        onClick={() => {
                          exportData(id as string, 'excel', stats, projectName);
                          document.getElementById('export-menu')?.classList.add('hidden');
                        }}
                        className="text-gray-700 block w-full text-left px-4 py-2 text-sm hover:bg-gray-100"
                        role="menuitem"
                      >
                        Excel格式
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            }
          />
        </div>
        
        {showFilters && (
          <div className="mt-4 bg-white shadow overflow-hidden sm:rounded-lg">
            <div className="px-4 py-5 sm:p-6">
              <h3 className="text-lg leading-6 font-medium text-gray-900">
                筛选选项
              </h3>
              <div className="mt-5 grid grid-cols-1 gap-5 sm:grid-cols-3">
                <div>
                  <label htmlFor="date-range" className="block text-sm font-medium text-gray-700">
                    时间范围
                  </label>
                  <select
                    id="date-range"
                    name="date-range"
                    className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md"
                    value={filter.dateRange}
                    onChange={(e) => setFilter({ ...filter, dateRange: e.target.value as any })}
                  >
                    <option value="week">最近一周</option>
                    <option value="month">最近一个月</option>
                    <option value="quarter">最近三个月</option>
                    <option value="year">最近一年</option>
                    <option value="custom">自定义范围</option>
                  </select>
                </div>
                
                <div>
                  <label htmlFor="members" className="block text-sm font-medium text-gray-700">
                    团队成员
                  </label>
                  <select
                    id="members"
                    name="members"
                    className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md"
                    defaultValue=""
                  >
                    <option value="">所有成员</option>
                    {stats?.memberActivity.map(member => (
                      <option key={member.userId} value={member.userId}>
                        {member.name}
                      </option>
                    ))}
                  </select>
                </div>
                
                <div>
                  <label htmlFor="task-status" className="block text-sm font-medium text-gray-700">
                    任务状态
                  </label>
                  <select
                    id="task-status"
                    name="task-status"
                    className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md"
                    defaultValue=""
                  >
                    <option value="">所有状态</option>
                    <option value="todo">待处理</option>
                    <option value="in-progress">进行中</option>
                    <option value="review">审核中</option>
                    <option value="done">已完成</option>
                  </select>
                </div>
              </div>
              <div className="mt-5 flex justify-end">
                <button
                  type="button"
                  onClick={() => {
                    // 重新加载数据
                    loadStats();
                  }}
                  className="ml-3 inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none"
                >
                  应用筛选
                </button>
              </div>
            </div>
          </div>
        )}
        
        {loading ? (
          <div className="mt-8 flex justify-center">
            <div className="animate-pulse text-gray-500">正在加载项目统计数据...</div>
          </div>
        ) : error ? (
          <div className="mt-8 text-center py-12 px-4">
            <div className="text-red-500 text-lg mb-4">{error}</div>
            <button
              onClick={loadStats}
              className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none"
            >
              重试
            </button>
          </div>
        ) : stats ? (
          <>
            {/* 统计摘要卡片 */}
            <div className="mt-8 grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4">
              {/* 任务完成率 */}
              <div className="bg-white overflow-hidden shadow rounded-lg">
                <div className="p-5">
                  <div className="flex items-center">
                    <div className="flex-shrink-0 bg-blue-500 rounded-md p-3">
                      <ChartBarIcon className="h-6 w-6 text-white" aria-hidden="true" />
                    </div>
                    <div className="ml-5 w-0 flex-1">
                      <dl>
                        <dt className="text-sm font-medium text-gray-500 truncate">任务完成率</dt>
                        <dd>
                          <div className="text-lg font-medium text-gray-900">
                            {completionPercentage}%
                          </div>
                          <div className="mt-1 flex items-baseline">
                            <span className="text-sm text-gray-600">
                              {stats.taskCompletion.completed}/{stats.taskCompletion.total} 已完成
                            </span>
                          </div>
                        </dd>
                      </dl>
                    </div>
                  </div>
                </div>
                <div className="bg-gray-50 px-5 py-3">
                  <div className="w-full bg-gray-200 rounded-full h-2.5">
                    <div
                      className="bg-blue-600 h-2.5 rounded-full"
                      style={{ width: `${completionPercentage}%` }}
                    ></div>
                  </div>
                </div>
              </div>

              {/* 项目时间 */}
              <div className="bg-white overflow-hidden shadow rounded-lg">
                <div className="p-5">
                  <div className="flex items-center">
                    <div className="flex-shrink-0 bg-green-500 rounded-md p-3">
                      <ClockIcon className="h-6 w-6 text-white" aria-hidden="true" />
                    </div>
                    <div className="ml-5 w-0 flex-1">
                      <dl>
                        <dt className="text-sm font-medium text-gray-500 truncate">项目耗时</dt>
                        <dd>
                          <div className="text-lg font-medium text-gray-900">
                            {timeProgress}%
                          </div>
                          <div className="mt-1 flex items-baseline">
                            <span className="text-sm text-gray-600">
                              {stats.timeTracking.actualHours}h/{stats.timeTracking.estimatedHours}h 预计
                            </span>
                          </div>
                        </dd>
                      </dl>
                    </div>
                  </div>
                </div>
                <div className="bg-gray-50 px-5 py-3">
                  <div className="w-full bg-gray-200 rounded-full h-2.5">
                    <div
                      className="bg-green-600 h-2.5 rounded-full"
                      style={{ width: `${timeProgress}%` }}
                    ></div>
                  </div>
                </div>
              </div>
              
              {/* 活跃成员 */}
              <div className="bg-white overflow-hidden shadow rounded-lg">
                <div className="p-5">
                  <div className="flex items-center">
                    <div className="flex-shrink-0 bg-purple-500 rounded-md p-3">
                      <UserGroupIcon className="h-6 w-6 text-white" aria-hidden="true" />
                    </div>
                    <div className="ml-5 w-0 flex-1">
                      <dl>
                        <dt className="text-sm font-medium text-gray-500 truncate">团队成员</dt>
                        <dd>
                          <div className="text-lg font-medium text-gray-900">
                            {stats.memberActivity.length}
                          </div>
                          <div className="mt-1 flex items-baseline">
                            <span className="text-sm text-gray-600">
                              活跃成员
                            </span>
                          </div>
                        </dd>
                      </dl>
                    </div>
                  </div>
                </div>
                <div className="bg-gray-50 px-5 py-3">
                  <button
                    type="button"
                    onClick={() => setShowFilters(true)}
                    className="text-sm text-blue-600 hover:text-blue-800"
                  >
                    查看成员详情
                  </button>
                </div>
              </div>
              
              {/* 剩余工时 */}
              <div className="bg-white overflow-hidden shadow rounded-lg">
                <div className="p-5">
                  <div className="flex items-center">
                    <div className="flex-shrink-0 bg-amber-500 rounded-md p-3">
                      <CalendarDaysIcon className="h-6 w-6 text-white" aria-hidden="true" />
                    </div>
                    <div className="ml-5 w-0 flex-1">
                      <dl>
                        <dt className="text-sm font-medium text-gray-500 truncate">剩余工时</dt>
                        <dd>
                          <div className="text-lg font-medium text-gray-900">
                            {stats.timeTracking.remainingHours}h
                          </div>
                          <div className="mt-1 flex items-baseline">
                            <span className="text-sm text-gray-600">
                              还需完成
                            </span>
                          </div>
                        </dd>
                      </dl>
                    </div>
                  </div>
                </div>
                <div className="bg-gray-50 px-5 py-3">
                  <div className="text-sm text-gray-500">
                    总计划: {stats.timeTracking.estimatedHours}h
                  </div>
                </div>
              </div>
            </div>
            
            {/* 任务状态分布 */}
            <div className="mt-8 bg-white shadow overflow-hidden sm:rounded-lg">
              <div className="px-4 py-5 sm:px-6">
                <h3 className="text-lg leading-6 font-medium text-gray-900">
                  任务状态分布
                </h3>
                <p className="mt-1 max-w-2xl text-sm text-gray-500">
                  各状态下的任务数量
                </p>
              </div>
              <div className="px-4 py-5 sm:p-6">
                <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
                  {stats.taskCompletion && stats.taskCompletion.byStatus && Object.entries(stats.taskCompletion.byStatus).map(([status, count]) => (
                    <div key={status} className="bg-gray-50 rounded-lg p-4">
                      <div className="flex items-center">
                        <div className={`h-4 w-4 rounded-full mr-2 ${getStatusColor(status)}`}></div>
                        <h4 className="text-sm font-medium text-gray-900">{getStatusName(status)}</h4>
                      </div>
                      <p className="mt-2 text-lg font-semibold">{count}</p>
                      <p className="text-xs text-gray-500">
                        {stats.taskCompletion.total > 0 ? Math.round((count / stats.taskCompletion.total) * 100) : 0}% 的任务
                      </p>
                    </div>
                  ))}
                </div>
              </div>
            </div>
            
            {/* 团队成员活动 */}
            <div className="mt-8 bg-white shadow overflow-hidden sm:rounded-lg">
              <div className="px-4 py-5 sm:px-6">
                <h3 className="text-lg leading-6 font-medium text-gray-900">
                  团队成员活动
                </h3>
                <p className="mt-1 max-w-2xl text-sm text-gray-500">
                  成员贡献和活动情况
                </p>
              </div>
              <div className="px-4 py-5 sm:p-6">
                <div className="flex flex-col">
                  <div className="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
                    <div className="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
                      <div className="shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">
                        <table className="min-w-full divide-y divide-gray-200">
                          <thead className="bg-gray-50">
                            <tr>
                              <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                成员
                              </th>
                              <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                完成任务
                              </th>
                              <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                评论数
                              </th>
                              <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                最后活动
                              </th>
                            </tr>
                          </thead>
                          <tbody className="bg-white divide-y divide-gray-200">
                            {stats.memberActivity.map((member) => (
                              <tr key={member.userId}>
                                <td className="px-6 py-4 whitespace-nowrap">
                                  <div className="flex items-center">
                                    <div className="flex-shrink-0 h-10 w-10 bg-gray-200 rounded-full overflow-hidden">
                                      <div className="h-full w-full flex items-center justify-center text-gray-500 font-medium text-lg">
                                        {member.name.charAt(0)}
                                      </div>
                                    </div>
                                    <div className="ml-4">
                                      <div className="text-sm font-medium text-gray-900">
                                        {member.name}
                                      </div>
                                    </div>
                                  </div>
                                </td>
                                <td className="px-6 py-4 whitespace-nowrap">
                                  <div className="text-sm text-gray-900">{member.tasksCompleted}</div>
                                </td>
                                <td className="px-6 py-4 whitespace-nowrap">
                                  <div className="text-sm text-gray-900">{member.commentsAdded}</div>
                                </td>
                                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                  {formatDate(member.lastActive)}
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </>
        ) : (
          renderNoData()
        )}
      </main>
    </div>
  );
}

// 辅助函数：获取任务状态颜色
const getStatusColor = (status: string) => {
  switch (status) {
    case 'todo':
      return 'bg-gray-400';
    case 'in-progress':
      return 'bg-blue-400';
    case 'review':
      return 'bg-amber-400';
    case 'done':
      return 'bg-green-400';
    default:
      return 'bg-gray-400';
  }
};

// 辅助函数：获取任务状态名称
const getStatusName = (status: string) => {
  switch (status) {
    case 'todo':
      return '待处理';
    case 'in-progress':
      return '进行中';
    case 'review':
      return '审核中';
    case 'done':
      return '已完成';
    default:
      return status;
  }
};

// 格式化日期
const formatDate = (date: string | Date) => {
  const d = new Date(date);
  return d.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  });
}; 